/**
 * 
 */
package com.xpec.c4.game.time;

import java.util.Date;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.xpec.c4.service.module.ServerProperties;

/**
 * 作業系統
 * 
 * @author lipeilin
 * @2011-4-26 下午02:29:51
 * 
 */
public class JobExecutor {

	private static final JobSchedule jobManager = new JobSchedule(
			ServerProperties.getInt("GlobalScheduleSize", 5));

	static {
		// jobManager.
	}

	/**
	 * 定時執行的任務<br>
	 * 自定義單位
	 * 
	 * @param task
	 * @param delay
	 * @param unit
	 * 
	 * @author lipeilin
	 * @2011-4-26 下午02:34:21
	 */
	public static RunnableScheduledFuture<?> schedule(Runnable task,
			long delay, TimeUnit unit) {
		return (RunnableScheduledFuture<?>) jobManager.schedule(task, delay,
				unit);
	}

	/**
	 * 定時執行的任務<br>
	 * 自定義單位
	 * 
	 * @param task
	 * @param delay
	 * @param unit
	 * 
	 * @author lipeilin
	 * @2011-4-26 下午02:34:21
	 */
	public static RunnableScheduledFuture<?> schedule(Runnable task, Date date,
			TimeUnit unit) {
		long initialDelay = date.getTime() - TimeSys.currentTimeMills();
		return (RunnableScheduledFuture<?>) schedule(task, initialDelay,
				TimeUnit.MILLISECONDS);

	}

	/**
	 * 定時執行的任務<br>
	 * 自定義單位
	 * 
	 * @param task
	 * @param delay
	 * @param unit
	 * 
	 * @author lipeilin
	 * @2011-4-26 下午02:34:21
	 */
	public static RunnableScheduledFuture<?> scheduleAtFixedRate(Runnable task,
			long initialDelay, long period, TimeUnit unit) {
		return (RunnableScheduledFuture<?>) jobManager.scheduleAtFixedRate(
				task, initialDelay, period, unit);
	}

	/**
	 * 固定周期执行
	 * 
	 * @param task
	 * @param initialDelay
	 * @param period
	 * 
	 * @author lipeilin
	 * @2011-4-28 下午06:27:39
	 */
	public static RunnableScheduledFuture<?> scheduleAtFixedRate(Runnable task,
			long initialDelay, long period) {
		return (RunnableScheduledFuture<?>) scheduleAtFixedRate(task,
				initialDelay, period, TimeUnit.MILLISECONDS);
	}

	public static RunnableScheduledFuture<?> scheduleAtFixedRate(Runnable task,
			Date date, long period) {
		long initialDelay = date.getTime() - TimeSys.currentTimeMills();
		return (RunnableScheduledFuture<?>) scheduleAtFixedRate(task,
				initialDelay, period, TimeUnit.MILLISECONDS);
	}

	/**
	 * 立即执行
	 * 
	 * @param task
	 * 
	 * @author lipeilin
	 * @2011-4-28 下午06:27:41
	 */
	public static void execute(Runnable task) {
		jobManager.execute(task);
	}

	/**
	 * 定時執行的任務<br>
	 * 單位:秒
	 * 
	 * @param task
	 * @param delay
	 * 
	 * @author lipeilin
	 * @2011-4-26 下午02:33:47
	 */
	public static RunnableScheduledFuture<?> schedule(Runnable task, long delay) {
		return (RunnableScheduledFuture<?>) jobManager.schedule(task, delay,
				TimeUnit.MILLISECONDS);
	}

	/**
	 * 任务移除
	 * 
	 * @param task
	 * 
	 * @author lipeilin
	 * @2011-4-26 下午03:31:02
	 */
	public static void remove(Runnable task) {
		if (task != null) {
			jobManager.remove(task);
		}
	}
	
	public static void shutdown() {
		jobManager.shutdown();
	}

}
